package com.gec.it.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.util.FileUtil;
import org.activiti.engine.task.Comment;
import com.gec.it.entity.Doctors;
import com.gec.it.entity.Plans;
import com.gec.it.service.DoctorsService;
import com.gec.it.service.PlansService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.gec.it.service.ApproveService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class ApproveController {
    @Autowired
    private ApproveService service;
    @Autowired
    private PlansService plansService;
    @Autowired
    private DoctorsService doctorsService;

    //	@ResponseBody
//	@GetMapping("/approve/ajax/comments")
//	public List<Comment> ajaxComments(int askid){
//		return service.findCommentByBizkey("borrow",askid+"");
//	}
    //-------------------------------------权限修改审批信息--------------------------
    @GetMapping("/approve/change")
    public String edit(int pid, Model m) {
        Plans plan = plansService.getById2(pid);
        m.addAttribute("p", plan);
        return "plan_edit";
    }
    @PostMapping("/approve/change")
    public String edit(String name, Plans plans) {
        System.out.println("time:"+plans.getPlanDate());
        if(plans.getPlanDate()==null){
            plans.setPlanDate(new Date());
        }
        Doctors doc = doctorsService.getById2(plans.getPlanDocId());
        doc.setDocName(name);
        doctorsService.updateById(doc);
        plansService.updateById(plans);
        return "redirect:/approve/mytask";
    }
    //---------------------------------------用户撤销---------------------------
    @GetMapping("/cancel")
    public String cancel(int askid) {
        service.cancelByBizkey("hp", askid + "");
        Plans br = plansService.getById2(askid);
        br.setPlanWfState("用户撤销");
        br.setPlanState(2);
        plansService.updateById(br);
        return "redirect:plans/list";
    }

    //-----------------------------------------------打开审批列表-----------------------------------
    @GetMapping("/approve/pass")
    public String pass(int askid, String taskid, Model m) {
        Plans br = plansService.getById2(askid);
        m.addAttribute("ask", br);

        List<String> btns = service.findOutComeListByTaskId(taskid);
        m.addAttribute("btns", btns);//把输出线的名字输出到jsp页面

        Task task = service.findTaskById(taskid);
        m.addAttribute("task", task);

        List<Comment> cmList = service.findCommentByTask(task);
        m.addAttribute("cmList", cmList);

        return "flow_approve";
    }

    //
    @PostMapping("/approve/pass")
    public String pass(int askid, String taskid, String comment, String result, Model m) {
        Doctors user = (Doctors) SecurityUtils.getSubject().getPrincipal();//获取当前登录用户
        Plans br = plansService.getById(askid);
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        Task next = service.saveSubmitTask(taskid, user.getUserkey(), comment, map);

        if (next != null) {
            br.setPlanWfState(next.getName());
        } else if (result.equals("同意")) {
            br.setPlanWfState("完成");//如果没有下一个节点就是完成了
        } else {
            br.setPlanWfState("结束流程");
        }
        plansService.updateById(br);

        return "redirect:/approve/mytask";
    }


    //显示任务列表(包含asks表的数据和工作流act_ru_task的数据)----------------------------------------------
    @GetMapping("/approve/mytask")
    public String showMyTask(Model m) {
        Doctors user = (Doctors) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user.getUserkey());
        List<Task> taskList = service.findTaskListByName("hp", user.getUserkey());
        System.out.println(taskList);////
        List<Plans> brList = new ArrayList<>();
        for (Task t : taskList) {
            String bizkey = service.findBizkeyByTask(t);
            Plans b = plansService.getById(bizkey);
            //把task压入plans的扩展字段里;
            b.setTask(t);
            brList.add(b);
        }
        System.out.println(brList);/////
        m.addAttribute("brList", brList);//计划表的集合

        List<Task> groupList = service.findGroupTaskListByName("hp", user.getUserkey());
        List<Plans> groupBrList = new ArrayList<>();
        for (Task t : groupList) {
            String bizkey = service.findBizkeyByTask(t);
            Plans a = plansService.getById2(bizkey);
            //把task压入asks的扩展字段里;
            a.setTask(t);
            List<IdentityLink> links = service.findGroupUsers(t.getId());//找到哪些人有资格审批这些任务
            a.setGroupLinks(links);
            groupBrList.add(a);
        }
        m.addAttribute("groupBrList", groupBrList);
        return "flow_mytasks";
    }

    //--------------------------------------查看审批信息--得到红框坐标-----------------------------------------
    @GetMapping("/plans/now")
    public String showImage(int askid, Model m) {
        List<Map<String, Object>> list = service.findCoordingByBizkey("hp", askid + "");
        m.addAttribute("askid", askid);
        m.addAttribute("list", list);
        return "flow_Image";
    }

    //------------------------------------展示流程图-----------------------------------------------------
    @GetMapping("/plans/picture")
    public void startWorkflow(int askid, HttpServletResponse resp) throws IOException {
        System.out.println("123");
        resp.setContentType("image/jpeg");
        InputStream in = service.findImageInputStreamByBizkey("hp", askid + "");
        OutputStream os = resp.getOutputStream();
        FileUtil.copyStream(in, os);
        os.flush();
        os.close();
    }

    //---------------------------------------开始查询流程图-------------------------------------
    @GetMapping("/plans/approve_start")
    public String startWorkflow(int pid) {
        Doctors user = (Doctors) SecurityUtils.getSubject().getPrincipal();
        if (service.findHisProcByBizkey("hp", pid + "") != null) {
            throw new RuntimeException("已经开启过此工作流");
        }

        Plans b = plansService.getById(pid);

        Map<String, Object> map = new HashMap<String, Object>();//准备要压入一些数据到流程图中（当前用户是谁，报销金额是多少）；
        map.put("userkey", user.getUserkey());//当前用户
        map.put("fee", b.getPlanFee());

        service.startWorkflow("hp", pid, map);
        //同时修改业务对象的状态
        b.setPlanWfState("准备提交");
        plansService.updateById(b);
        return "redirect:/approve/mytask";//跳转到我的任务
    }

    //---------------------------------------上传流程图（borrow）--------------------------------
    @GetMapping("/deploy")
    public String deploy() {
        return "flow_add";
    }

    @PostMapping("/deploy")
    public String deploy(String name, MultipartFile design) throws IOException {

        service.deploy(name, design.getInputStream());
        return "redirect:/deploy_list";
    }

    @GetMapping("/deploy_list")
    public String deployList(Model m) {
        List<Deployment> list = service.findDeploys();
        m.addAttribute("list", list);
        return "flow_list";
    }

    @GetMapping("/admin/del")
    public String del(String id) {
        service.removeDeploy(id);
        return "redirect:/flow_list";
    }

}



